﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Dln.Common;
using Newtonsoft.Json;


namespace Dln.Handler
{
    public class WeiXinConfig
    {
        private static DateTime GetAccessToken_Time;
        /// <summary>
        /// 过期时间为3600秒
        /// </summary>
        private static int Expires_Period = 300;
        /// <summary>
        /// AppID
        /// </summary>
        public static string AppID
        {
            get
            {
                return CommonHelper.GetAppSettings("AppID");
            }
        }
        /// <summary>
        /// AppSecret
        /// </summary>
        public static string AppSecret
        {
            get
            {
                return CommonHelper.GetAppSettings("AppSecret");
            }
        }
        /// <summary>
        /// Token
        /// </summary>
        public static string Token
        {
            get
            {
                return CommonHelper.GetAppSettings("token");
            }
        }

        public static string MainUrl
        {
            get
            {
                return CommonHelper.GetAppSettings("mainurl");
            }
        }
        private static string mAccessToken;
        /// <summary>
        /// AccessToken
        /// </summary>
        public static string AccessToken
        {
            get
            {
                //如果为空，或者过期，需要重新获取
                if (string.IsNullOrEmpty(mAccessToken) || HasExpired())
                {
                    mAccessToken = GetAccessToken();//获取
                }
                return mAccessToken;
            }
        }
        
        private static string GetAccessToken()
        {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("--{0} 调用方法GetAccessToken(),获取token。", DateTime.Now.ToString());
                string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret);
                string result = RequestHelper.SendGet(url);
                XDocument doc = JsonConvert.DeserializeXNode(result, "root");
                XElement root = doc.Root;
                if (root != null)
                {
                    XElement access_token = root.Element("access_token");
                    if (access_token != null)
                    {
                        GetAccessToken_Time = DateTime.Now;
                        if (root.Element("expires_in") != null)
                        {
                            //Expires_Period = int.Parse(root.Element("expires_in").Value);
                        }
                        sb.AppendFormat("token获取成功，值为：{0}", access_token.Value);
                        //redisClient.Set<string>("XSaccess_token", access_token.Value);
                        //redisClient.Dispose();
                        return access_token.Value;
                    }
                    else
                    {
                        sb.Append("access_token为null。");
                        GetAccessToken_Time = DateTime.MinValue;
                    }
                }
                else
                {
                    sb.Append("root为null。");
                }
                return null;
        }
        /// <summary>
        /// 判断Access_token是否过期
        /// </summary>
        /// <returns>bool</returns>
        private static bool HasExpired()
        {
            if (GetAccessToken_Time != null)
            {
                //过期时间，允许有一定的误差，一分钟。获取时间消耗
                if (DateTime.Now > GetAccessToken_Time.AddSeconds(Expires_Period).AddSeconds(-60))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
